package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 黄晏凯
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 文章搜索
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //搜索关键字
        if (StringUtils.isNotEmpty(dto.getSearchWords())) {
            boolQueryBuilder.must(QueryBuilders
                    .queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR)
            );
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //时间范围
        boolQueryBuilder.filter(QueryBuilders
                .rangeQuery("publishTime")
                .lt(dto.getMinBehotTime())
        );

        sourceBuilder.query(boolQueryBuilder);

        //设置分页
        sourceBuilder.from(dto.getPageNum() * dto.getPageSize());
        sourceBuilder.size(dto.getPageSize());

        //设置高亮
        sourceBuilder.highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        sourceBuilder.sort("publishTime",SortOrder.DESC);

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] searchHits = hits.getHits();
        List<Map> list = null;
        if (null != searchHits && searchHits.length > 0) {
            list = new ArrayList<>(searchHits.length);
            for (SearchHit searchHit : searchHits) {
                String json = searchHit.getSourceAsString();
                Map map = JSON.parseObject(json, Map.class);

                //解析高亮数据
                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                if (null != highlightFields && highlightFields.size() > 0) {
                    HighlightField highlightField = highlightFields.get("title");
                    Text[] fragments = highlightField.getFragments();

                    map.put("h_title", StringUtils.join(fragments));
                } else {
                    map.put("h_title", map.get("title"));
                }

                list.add(map);
            }
        }

        return ResponseResult.okResult(list);
    }
}